<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h3>Personal Information</h3>
          <el-button type="primary" @click="handleSave" :loading="loading" v-if="activeTab === 'profile'">Save Changes</el-button>
          <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading" v-if="activeTab === 'password'">Change Password</el-button>
        </div>
      </template>

      <div class="profile-content">
        <div class="avatar-container">
          <el-upload
            class="avatar-uploader"
            action="/api/user/avatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-error="handleAvatarError"
            :headers="uploadHeaders"
          >
            <el-avatar
              :size="100"
              :src="form.avatar || userStore.user.avatar"
              class="avatar"
            >
              {{ userStore.user.username?.charAt(0).toUpperCase() }}
            </el-avatar>
            <div class="avatar-upload-tip">Click to change avatar</div>
          </el-upload>
        </div>

        <el-tabs v-model="activeTab" type="card">
          <el-tab-pane label="Profile" name="profile">
            <el-form
              ref="formRef"
              :model="form"
              :rules="rules"
              label-width="100px"
              class="profile-form"
            >
              <el-form-item label="Username">
                <el-input v-model="displayUsername" disabled />
              </el-form-item>

              <el-form-item label="Real Name" prop="realName">
                <el-input v-model="form.realName" placeholder="Enter your real name" />
              </el-form-item>

              <el-form-item label="Nickname" prop="nickname">
                <el-input v-model="form.nickname" placeholder="Enter your nickname" />
              </el-form-item>

              <el-form-item label="Email" prop="email">
                <el-input v-model="form.email" placeholder="Enter your email" />
              </el-form-item>

              <el-form-item label="Phone" prop="phone">
                <el-input v-model="form.phone" placeholder="Enter your phone number" />
              </el-form-item>

              <el-form-item label="Bio" prop="bio">
                <el-input
                  v-model="form.bio"
                  type="textarea"
                  :rows="4"
                  placeholder="Enter your bio"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
          
          <el-tab-pane label="Change Password" name="password">
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-width="150px"
              class="password-form"
            >
              <el-form-item label="Current Password" prop="currentPassword">
                <el-input
                  v-model="passwordForm.currentPassword"
                  type="password"
                  placeholder="Enter current password"
                  show-password
                />
              </el-form-item>

              <el-form-item label="New Password" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="Enter new password"
                  show-password
                />
              </el-form-item>

              <el-form-item label="Confirm Password" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="Confirm new password"
                  show-password
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <el-card class="profile-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <h3>Role Information</h3>
        </div>
      </template>

      <div class="role-info">
        <el-tag
          v-for="role in userStore.user.roles"
          :key="role"
          :type="role === 'ADMIN' ? 'danger' : 'success'"
          class="role-tag"
        >
          {{ role }}
        </el-tag>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import type { FormInstance, UploadProps } from 'element-plus'
import type { UpdateProfileRequest, UpdatePasswordRequest } from '../types/user'

const userStore = useUserStore()
const formRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()
const loading = ref(false)
const passwordLoading = ref(false)
const activeTab = ref('profile')

const form = reactive<UpdateProfileRequest & { avatar?: string }>({
  realName: userStore.user.realName || '',
  nickname: userStore.user.nickname || '',
  email: userStore.user.email || '',
  phone: userStore.user.phone || '',
  bio: userStore.user.bio || '',
  avatar: userStore.user.avatar || ''
})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  realName: [
    { required: true, message: 'Please enter your real name', trigger: 'blur' },
    { min: 2, max: 20, message: 'Length should be 2 to 20 characters', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: 'Please enter your nickname', trigger: 'blur' },
    { min: 2, max: 20, message: 'Length should be 2 to 20 characters', trigger: 'blur' }
  ],
  email: [
    { required: true, message: 'Please enter your email', trigger: 'blur' },
    { type: 'email', message: 'Please enter a valid email address', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: 'Please enter your phone number', trigger: 'blur' },
    { pattern: /^[0-9]{10,15}$/, message: 'Please enter a valid phone number', trigger: 'blur' }
  ],
  bio: [
    { max: 200, message: 'Bio cannot exceed 200 characters', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: 'Please enter current password', trigger: 'blur' },
    { min: 6, message: 'Password length cannot be less than 6 characters', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: 'Please enter new password', trigger: 'blur' },
    { min: 6, message: 'Password length cannot be less than 6 characters', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: 'Please confirm new password', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('The two passwords do not match'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const uploadHeaders = computed(() => {
  return {
    Authorization: `Bearer ${userStore.token}`
  }
})

const handleSave = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const profileData = {
          realName: form.realName,
          nickname: form.nickname,
          email: form.email,
          phone: form.phone,
          bio: form.bio
      
        }
        
        console.log('Submitting profile data:', profileData)
        
        const success = await userStore.updateProfile(profileData)
        if (success) {
          ElMessage.success('Profile updated successfully')
          
          form.realName = userStore.user.realName || ''
          form.nickname = userStore.user.nickname || ''
          form.email = userStore.user.email || ''
          form.phone = userStore.user.phone || ''
          form.bio = userStore.user.bio || ''
          form.avatar = userStore.user.avatar || ''
        } else {
          ElMessage.error(userStore.error || 'Failed to update profile')
        }
      } catch (error: any) {
        console.error('Failed to save profile:', error)
        const errorMsg = error.response?.data?.message || 'Failed to save profile, please try again later'
        ElMessage.error(errorMsg)
      } finally {
        loading.value = false
      }
    }
  })
}

const handleChangePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        const data: UpdatePasswordRequest = {
          currentPassword: passwordForm.currentPassword,
          newPassword: passwordForm.newPassword
        }
        await userStore.changePassword(data)
        ElMessage.success('Password changed successfully')
        passwordForm.currentPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
        passwordFormRef.value.clearValidate()
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || 'Failed to change password')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}


const handleAvatarSuccess = (response: any) => {
  if (response && response.url) {

    form.avatar = response.url

    userStore.user.avatar = response.url
    

    userStore.updateAvatar(response.url)
      .then(success => {
        if (success) {
          ElMessage.success('Avatar uploaded successfully')
        } else {
          ElMessage.error('Avatar uploaded but failed to save')
        }
      })
      .catch(error => {
        console.error('Failed to save avatar:', error)
        ElMessage.error('Avatar uploaded but failed to save')
      })
  } else {
    ElMessage.error('Avatar upload response format error')
    console.error('Avatar upload response format error:', response)
  }
}

const handleAvatarError = (error: any) => {
  console.error('Avatar upload failed:', error)
  ElMessage.error('Avatar upload failed, please try again later')
}

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('Avatar can only be JPG or PNG format!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('Avatar size cannot exceed 2MB!')
    return false
  }
  return true
}

const displayUsername = computed(() => {
  return userStore.user.username || 
         (userStore.userInfo && userStore.userInfo.username) || 
         'Username not set'
})

// Get the latest user information when the component is mounted
onMounted(async () => {
  try {
    // Force refresh user information to ensure data is up-to-date
    await userStore.fetchUserInfo(true)
    console.log('User information updated:', userStore.user)
  } catch (error) {
    console.error('Failed to get user information:', error)
    ElMessage.error('Failed to get user information, please try again later')
  }
})
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  max-height: 80vh; /* Set a maximum height relative to viewport height */
  overflow-y: auto; /* Enable vertical scrolling */
}

.profile-card {
  background-color: #fff;
  border-radius: 4px;
}

/* Custom scrollbar styling for the main container */
.profile-container::-webkit-scrollbar {
  width: 6px;
}

.profile-container::-webkit-scrollbar-thumb {
  background-color: #909399;
  border-radius: 3px;
}

.profile-container::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.profile-content {
  display: flex;
  gap: 40px;
  padding: 20px 0;
}

.avatar-container {
  text-align: center;
}

.avatar-uploader {
  cursor: pointer;
}

.avatar {
  display: block;
  margin-bottom: 10px;
}

.avatar-upload-tip {
  color: #909399;
  font-size: 12px;
}

.profile-form {
  flex: 1;
}

.password-form {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px 0;
}

.role-info {
  padding: 20px 0;
}

.role-tag {
  margin-right: 10px;
}

:deep(.el-upload) {
  cursor: pointer;
}

:deep(.el-upload:hover) {
  border-color: #409EFF;
}

/* Remove previous scrollable content styles that target individual sections */
/* Ensure form elements display correctly */
.profile-form, .password-form {
  padding-bottom: 10px;
}
</style> 